/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
 // 层遍历 ：递归算法
func levelOrder(root *TreeNode) [][]int {
    res := [][]int{}
    if root == nil {
        return res
    }

    var traverse func (node *TreeNode, depth int)
    traverse = func (node *TreeNode, depth int) {
        if node != nil {
            if len(res) == depth {
                res = append(res, []int{})
            }
            res[depth] = append(res[depth], node.Val)
        }
        if node.Left != nil {
            traverse(node.Left, depth+1)
        }
        if node.Right != nil {
            traverse(node.Right, depth+1)
        }
    }
    traverse(root, 0)
    return res
}